  <template>
    <div>
      <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>客户账户管理</el-breadcrumb-item>
      </el-breadcrumb>
      <el-card>
        <!-- 页面标题 -->
        <el-page-header @back="goBack" content="客户账户列表" style="margin-bottom: 20px;"></el-page-header>
        <!-- 多条件查询区 -->
        <el-form :inline="true" ref="form" size="small" style="margin-top: 2vh">
          <el-row>
            <h4 style="margin: 1vh 0 2vh;color: #1f2d3d">多条件查询区</h4>
          </el-row>
          <el-form-item>
            <el-input v-model="queryMap.clientName" clearable placeholder="请输入客户名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="queryMap.linkman" clearable placeholder="请输入联系人"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="queryMap.phone" clearable placeholder="请输入联系电话"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="queryMap.accountName" clearable placeholder="请输入账户名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="queryMap.company" clearable placeholder="请输入所属公司"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="queryMap.platformType" clearable placeholder="请输入平台类型"></el-input>
          </el-form-item>
          <el-form-item>
            <el-select v-model="queryMap.accountType" clearable placeholder="请选择账户类型">
              <el-option label="全部" value=""></el-option>
              <el-option label="正常" value="正常"></el-option>
              <el-option label="异常" value="异常"></el-option>
              <el-option label="关停" value="关停"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户种类" style="margin-left: 3vh">
            <el-select
                clearable
                style="width: 140px;"
                placeholder="请选择"
                v-model="queryMap.clientTypeId"
            >
              <el-option label="全部" value=""></el-option>
              <el-option v-for="dept in clienttypeList" :label="dept.options" :value="dept.clientTypeId">
              </el-option>
            </el-select>
            <el-button class="el-icon-s-cooperation dataDict" style="left: 18.5vh;"></el-button>
          </el-form-item>
          <el-form-item label="有效期">
            <el-date-picker
                v-model="indate"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="开户时间">
            <el-date-picker
                v-model="openDate"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-refresh" @click="reset" style="background-color: #f0f0f0; color: #409EFF; border: none;">重置</el-button>
            <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
          </el-form-item>
        </el-form>

        <!-- 操作按钮区 -->
        <div style="margin-bottom: 10px;display: flex">
          <span class="hint" style="flex: 1;"></span>
          <el-button v-hasPermission="'account:addAccount'" type="success" icon="el-icon-plus" @click="openAddDialog">新建账户</el-button>
        </div>

        <!-- 表格区域 -->
        <el-table ref="multipleTable" :data="accountData" size="small" @selection-change="handleSelectionChange"
                  border style="width: 100%;" height="420">
          <el-table-column type="selection" width="40"></el-table-column>
          <el-table-column prop="clientName" label="客户名称" width="150"></el-table-column>
          <el-table-column prop="linkman" label="联系人" width="120"></el-table-column>
          <el-table-column prop="phone" label="联系电话" width="150"></el-table-column>
          <el-table-column prop="accountName" label="账户名称" width="150"></el-table-column>
          <el-table-column prop="indate" label="账户有效期" width="150"></el-table-column>
            <el-table-column prop="company" label="所属公司" width="150"></el-table-column>
            <el-table-column prop="platformType" label="平台类型" width="100"></el-table-column>
            <el-table-column prop="accountType" label="账户类型" width="100"></el-table-column>
            <el-table-column prop="clienttype_options" label="客户类型" width="100"></el-table-column>
            <el-table-column prop="openDate" label="开户日期" width="150"></el-table-column>
            <el-table-column label="操作" width="350" fixed="right">
              <template slot-scope="scope">
                <el-tooltip content="编辑" placement="top" effect="light">
                  <el-button v-hasPermission="'account:updateAccount'" circle round plain size="small" type="primary" icon="el-icon-edit-outline" @click="openEditDialog(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top" effect="light">
                  <el-button v-hasPermission="'account:delete'" circle round plain icon="el-icon-delete" type="success" size="small" @click="deleteAccount(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="一键恢复" placement="top" effect="light">
                  <el-button v-hasPermission="'account:addUpdate'" circle round plain icon="el-icon-refresh" type="success" size="small" @click="updateUserByAccountName(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="一键清除" placement="top" effect="light">
                  <el-button v-hasPermission="'account:addDelete'" circle round plain icon="el-icon-delete" type="danger" size="small" @click="deleteUserByAccountName(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="账户高级设置" placement="top" effect="light">
                  <el-button v-hasPermission="'account:settings'" type="success" icon="el-icon-s-tools" @click="openSettingsWindows(scope.row)">账户高级设置</el-button>
                </el-tooltip>

              </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
            style="margin-top:10px;"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryMap.pageNum"
            :page-sizes="[6, 10, 20, 30]"
            :page-size="queryMap.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>

        <!-- 添加/编辑客户账户对话框 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" class="p2-style">
          <el-form :model="accountForm" :rules="formRules" ref="accountForm" label-width="120px" class="form-container">
            <el-row>
              <el-col :span="12">
  <!--          :rules="[{ required: true, message: '请输入客户编号', trigger: 'change' }]"    -->
                <el-form-item label="客户编号" prop="clientNo" >
                  <el-input v-model="accountForm.clientNo" clearable placeholder="请输入客户编号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="账户名称" prop="accountName">
                  <el-input
                      v-model="accountForm.accountName"
                      style="width: 100%;"
                      clearable
                      placeholder="请输入账户编号"
                      @blur="checkAccountName"
                      :disabled="dialogTitle === '修改账户'"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <!--          :rules="[{ required: true, message: '请输入客户编号', trigger: 'change' }]"    -->
                <el-form-item label="客户名称" prop="clientName" >
                  <el-input v-model="accountForm.clientName" clearable placeholder="请输入客户名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <!--            :rules="[{ required: true, message: '请输入账户名称', trigger: 'blur' }]"  -->
                <el-form-item label="联系人" prop="linkman" >
                  <el-input v-model="accountForm.linkman" style="width: 100%;" clearable placeholder="联系人"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <!--          :rules="[{ required: true, message: '请输入客户编号', trigger: 'change' }]"    -->
                <el-form-item label="联系方式" prop="phone" >
                  <el-input v-model="accountForm.phone" clearable placeholder="请输入电话号码"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <!--            :rules="[{ required: true, message: '请输入账户名称', trigger: 'blur' }]"  -->
                <el-form-item  label="部门" prop="deptId" v-if="showDeptSelect" >
                  <el-select
                      clearable
                      style="width: 140px;"
                      filterable
                      placeholder="请选择"
                      v-model="accountForm.deptId"
                  >
                    <el-option v-for="dept in deptClientList" :label="dept.deptName" :value="dept.deptId">
                    </el-option>
                  </el-select>
                  <el-tooltip effect="dark" placement="top"
                              content="只会显示没有使用的根部门">
                    <i class="el-icon-question" @click="$router.push({path:'/dept/ClientDept'})" ></i>
                  </el-tooltip>
                </el-form-item>
              </el-col>

            </el-row>
            <el-row>
              <el-col :span="12">
                <!--             :rules="[{ required: true, message: '请选择状态', trigger: 'change' }]" -->
                <el-form-item v-if="dialogTitle !== '新建账户'" label="状态" >
                  <el-select
                      clearable
                      style="width: 120px;"
                      v-model="accountForm.status"
                      placeholder="请选择状态"
                  >
                    <el-option label="正常" :value="0">正常</el-option>
                    <el-option label="冻结" :value="-1">冻结</el-option>
                    <el-option label="下线" :value="-2">下线</el-option>
                    <el-option label="已删除" :value="-3">已删除</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
  <!--             :rules="[{ required: true, message: '请输入账户有效期', trigger: 'change' }]" -->
                <el-form-item label="账户有效期"  prop="indate" >
                  <el-date-picker
                      prop="indate"
                      v-model="accountForm.indate"
                      type="datetime"
                      placeholder="选择日期时间"
                      value-format="yyyy-MM-dd HH:mm:ss">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="所属公司" prop="company">
                  <el-input v-model="accountForm.company" style="width: 100%;" clearable placeholder="请输入所属公司"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
  <!--        :rules="[{ required: true, message: '请选择平台类型', trigger: 'change' }]"      -->
                <el-form-item label="平台类型" prop="platformType" >
                  <el-input v-model="accountForm.platformType" style="width: 100%;" clearable placeholder="请输入平台类型"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
  <!--              :rules="[{ required: true, message: '请选择账户类型', trigger: 'change' }]"-->
                <el-form-item label="账户类型" prop="accountType" >
                  <el-select v-model="accountForm.accountType" clearable placeholder="请选择账户类型">
                    <el-option label="正常" value="正常"></el-option>
                    <el-option label="异常" value="异常"></el-option>
                    <el-option label="关停" value="关停"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
  <!--           :rules="[{ required: true, message: '请选择客户类型', trigger: 'change' }]"   -->
                <el-form-item label="客户类型" prop="clientTypeId" >
                  <el-select
                      clearable
                      style="width: 140px;"
                      placeholder="请选择"
                      v-model="accountForm.clientTypeId"
                  >
                    <el-option v-for="dept in clienttypeList" :label="dept.options" :value="dept.clientTypeId">
                    </el-option>
                  </el-select>
                </el-form-item>

              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
  <!--            :rules="[{ required: true, message: '请选择开户日期', trigger: 'change' }]"  -->
                <el-form-item label="开户日期" prop="openDate" >
                  <el-date-picker
                      prop="openDate"
                      v-model="accountForm.openDate"
                      type="datetime"
                      placeholder="选择日期时间"
                      value-format="yyyy-MM-dd HH:mm:ss">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item  label="所属售后" prop="employeeId_aftermarket">
                  <el-select
                      clearable
                      style="width: 140px;"
                      placeholder="请选择"
                      v-model="accountForm.employeeId_aftermarket"
                  >
                    <el-option v-for="dept in employeeList" :label="dept.nickName" :value="dept.empId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item  label="线路类型" prop="circuitId">
                  <el-select
                      clearable
                      style="width: 140px;"
                      placeholder="请选择"
                      v-model="accountForm.circuitId"
                  >
                    <el-option v-for="lineType in lineTypeList" :label="lineType.circuitType+'('+lineType.circuitTariff+')'" :value="lineType.circuitId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

            </el-row>
          </el-form>
          <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible=false">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :disabled="btnDisabled">{{dialogTitle === '新建账户'? '新建' : '保存' }}</el-button>
    </span>
          <div style="text-align: center; color: red; font-size: 12px; margin-top: 10px;">
            如果想要账户能够正常使用请立即进行高级设置
          </div>
        </el-dialog>



  <!--高级账户设置-->
        <el-dialog :visible.sync="settingsWindow" width="800px" class="p2-style">
          <el-form :model="accountForm" :rules="settingsRules" ref="accountForm" label-width="120px" class="form-container">
            <el-row>
              <el-col :span="12">
                <el-form-item label="签约座席数" prop="agentNum" >
                  <el-input type="number" v-model="accountForm.agentNum" clearable placeholder="请输入签约座席数"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="非套餐余额" prop="noPackageBalance" >
                  <el-input :precision="2" type="number" v-model="accountForm.noPackageBalance" clearable placeholder="请输入非套餐余额"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="注册地址" prop="regAddress" >
                  <el-input v-model="accountForm.regAddress" style="width: 100%;" clearable placeholder="注册地址"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="坐席月租" prop="agentMonthly" >
                  <el-input :precision="2"  v-model="accountForm.agentMonthly" clearable placeholder="坐席月租"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="号码费" prop="voucherNumber" >
                  <el-input :precision="2"   v-model="accountForm.voucherNumber" clearable placeholder="号码费"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="套餐费率" prop="packageRate" >
                  <el-input v-model="accountForm.packageRate" clearable placeholder="套餐费率"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="非套餐费率"  prop="noPackageRate" >
                  <el-input  type="number" v-model="accountForm.noPackageRate" clearable placeholder="非套餐费率"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="呼叫类型" prop="callType">
                  <el-input v-model="accountForm.callType" style="width: 100%;" clearable placeholder="请输入呼叫类型"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="应用KEY"  prop="appId" >
                  <el-input  v-model="accountForm.appId" clearable placeholder="请输入应用KEY"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="应用密钥" prop="appSecret">
                  <el-input type="password" v-model="accountForm.appSecret" style="width: 100%;" clearable placeholder="请输入应用密钥"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="话机密码" prop="phoneCode" >
                  <el-input v-model="accountForm.phoneCode" style="width: 100%;" clearable placeholder="话机密码"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="座席数" prop="seatsNumber" >
                  <el-input type="number"  v-model="accountForm.seatsNumber" style="width: 100%;" clearable placeholder="座席数"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <span slot="footer" class="dialog-footer">
      <el-button @click="settingsWindow =false;">取消</el-button>
      <el-button type="primary" @click="settingsSubmit">保存设置</el-button>


    </span>
        </el-dialog>
      </el-card>

    </div>
  </template>

  <script>
  import axios from "axios";

  export default {
    data() {
      return {
        settingsWindow:false,
        dialogVisible: false,
        dialogTitle: '新建账户',
        accountData: [],
        indate:[],
        openDate:[],
        clienttypeList:[],
        employeeList:[],
        deptClientList:[],
        circuitTypeList:[],
        btnLoading:false,
        btnDisabled:false,
        multipleSelection: [],
        lineTypeList:[],
        accountNameValid:true,
        count:0,
        total: 0,
        showDeptSelect: true,
        settingsRules: {
          appId:[
            {
              required: true,
              message: '应用KEY不能为空',
              trigger: 'blur'
            }
          ],
          appSecret:[
            {
              required: true,
              message: '应用密钥不能为空',
              trigger: 'blur'
            }
          ],
          agentNum: [
            { required: false, message: '', trigger: 'blur' }, // 允许为空
            {
              type: 'number',
              pattern: /^-?\d+$/,
              message: '请输入整数',
              trigger: 'blur',
              validator(rule, value, callback) {
                if (value === '' || value === null || value === undefined) {
                  return callback();
                }
                if (!rule.pattern.test(value)) {
                  return callback(new Error(rule.message));
                }
                callback();
              }
            }
          ],
          callType: [
            { required: false, message: '', trigger: 'blur' }, // 允许为空
            {
              type: 'number',
              pattern: /^-?\d+$/,
              message: '请输入整数',
              trigger: 'blur',
              validator(rule, value, callback) {
                if (value === '' || value === null || value === undefined) {
                  return callback();
                }
                if (!rule.pattern.test(value)) {
                  return callback(new Error(rule.message));
                }
                callback();
              }
            }
          ],
          noPackageBalance: [
            { required: false, message: '', trigger: 'blur' }, // 允许为空
            {
              type: 'string',
              pattern: /^\d+(\.\d{1,2})?$/,
              message: '小数点最多到后两位',
              trigger: 'blur',
              validator(rule, value, callback) {
                if (value === '' || value === null || value === undefined) {
                  return callback();
                }
                if (!rule.pattern.test(value)) {
                  return callback(new Error(rule.message));
                }
                callback();
              }
            }
          ],
          agentMonthly: [
            { required: false, message: '', trigger: 'blur' }, // 允许为空
            {
              type: 'string',
              pattern: /^\d+(\.\d{1,2})?$/,
              message: '小数点最多到后两位',
              trigger: 'blur',
              validator(rule, value, callback) {
                if (value === '' || value === null || value === undefined) {
                  return callback();
                }
                if (!rule.pattern.test(value)) {
                  return callback(new Error(rule.message));
                }
                callback();
              }
            }
          ],
          voucherNumber: [
            { required: false, message: '', trigger: 'blur' }, // 允许为空
            {
              type: 'string',
              pattern: /^\d+(\.\d{1,2})?$/,
              message: '小数点最多到后两位',
              trigger: 'blur',
              validator(rule, value, callback) {
                if (value === '' || value === null || value === undefined) {
                  return callback();
                }
                if (!rule.pattern.test(value)) {
                  return callback(new Error(rule.message));
                }
                callback();
              }
            }
          ],
          packageRate: [
            { required: false, message: '', trigger: 'blur' }, // 允许为空
            {
              type: 'string',
              pattern: /^\d+(\.\d{1,2})?$/,
              message: '套餐费率小数点最多到后两位',
              trigger: 'blur',
              validator(rule, value, callback) {
                if (value === '' || value === null || value === undefined) {
                  return callback();
                }
                if (!rule.pattern.test(value)) {
                  return callback(new Error(rule.message));
                }
                callback();
              }
            }
          ],
          noPackageRate: [
            { required: false, message: '', trigger: 'blur' }, // 允许为空
            {
              type: 'string',
              pattern: /^\d+(\.\d{1,2})?$/,
              message: '非套餐费率小数点最多到后两位',
              trigger: 'blur',
              validator(rule, value, callback) {
                if (value === '' || value === null || value === undefined) {
                  return callback();
                }
                if (!rule.pattern.test(value)) {
                  return callback(new Error(rule.message));
                }
                callback();
              }
            }
          ]
        },
        formRules: {
          circuitId:[
            {
              required: true, // 该字段必填
              message: '请选择线路类型',
              trigger: 'blur' // 失去焦点时触发验证
            }
          ],
          clientNo: [
            {
              required: true, // 该字段必填
              message: '请输入客户编号',
              trigger: 'blur' // 失去焦点时触发验证
            }
          ],
          deptId:[
            { required: true, message: '请选择部门', trigger: 'blur'}
          ],
          accountName: [
            // 这里可以按照类似思路为 highSeasCount 字段补充合适规则，比如要求是正整数等
            { required: true, message: '请输入账户名称', trigger: 'blur'}
          ],
          indate: [
            // 同样为 expiryDay 字段补充规则，例如限制天数范围等
            { required: true, message: '请选择账户有效期', trigger: 'blur' }
          ],
          openDate: [
            // 同样为 expiryDay 字段补充规则，例如限制天数范围等
            { required: true, message: '请选择开户日期', trigger: 'blur'}
          ],
          phone: [
            // 同样为 expiryDay 字段补充规则，例如限制天数范围等
            { required: true, message: '请输入电话号码', trigger: 'blur'},
            { pattern: /^\d{11}$/, message: '请输入 11 位数字的电话号码', trigger: 'blur' }
          ],
        }, //添加表单验证规则
        queryMap: {
          clientNo:"",
          clientName:"",
          linkman:"",
          phone:"",
          accountName:"",
          platformType:"",
          clientTypeId:"",
          accountType:"",
          clienttype_options:"",
          circuitId:"",
          openDateStartTime:"",
          openDateEndTime:"",
          status:null,
        },
        pickerOptions: {
          shortcuts: [
            {
              text: "最近一周",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "最近一个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "最近三个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit("pick", [start, end]);
              }
            }
          ]
        },
        accountForm: {
          clientNo:"",
          accountId: "",
          accountName: "",
          lineType: "",
          accountValidity: "",
          company: "",
          indate: "",
          platformType: "",
          accountType: "",
          employeeId_aftermarket:"",
          customerType: "",
          circuitType:"",
          circuit:"",
          circuitId:"",
          clientTypeId: null,  // 先初始化为 null 或一个默认值
          openDate: "",
          afterSales: "",
          appId:"",
          appSecret:"",
          accountBalance: "",
          status:null,
          seatsNumber:"",

          agentNum:"",
          noPackageBalance:"",
          packageBalance:"",
          agentMonthly:"",
          voucherNumber:"",
          packageRate:"",
          noPackageRate:"",
          callType:"",

          phoneCode:"",
          regAddress:"",
        },
        settingsForm:{
          accountId: "",
          agentNum:"",
          noPackageBalance:"",
          packageBalance:"",
          agentMonthly:"",
          voucherNumber:"",
          packageRate:"",
          noPackageRate:"",
          callType:"",
          phoneCode:"",
          regAddress:"",
        },
        customers: [
          { customerId: 'C001', clientName: '腾讯科技' },
          { customerId: 'C002', clientName: '阿里巴巴' },
          { customerId: 'C003', clientName: '华为' },
          { customerId: 'C004', clientName: '平安银行' },
          { customerId: 'C005', clientName: '华大基因' },
        ]
      };
    },
    methods: {
      // 其他方法
      handleSubmit() {
        if (!this.accountNameValid) {
          this.$message.error("账户名称不符合规则，请检查");
          return;
        }
        this.$refs.accountForm.validate((valid) => {
          if (valid) {
            if (this.dialogTitle === '新建账户') {
              this.addAccount();
            } else {
              this.updateAccount();
            }
          } else {
            this.$message.error('请检查表单输入是否完整或符合规则');
          }
        });
      },
      settingsSubmit() {
        this.$refs.accountForm.validate((valid) => {
          if (valid) {
            // 调用 settings 方法并处理可能的错误
            this.settings().catch((error) => {
              console.error('执行 settings 方法时出错:', error);
              this.$message.error('执行设置操作时遇到异常，请检查网络或联系管理员');
            });
          } else {
            this.$message.error('请检查表单输入是否完整或符合规则');
          }
        });
      },
      // 返回上一页
      goBack() {
        console.log("返回上一页");
      },
      async getAccountList() {
        this.loading = true;
        try {
          const res = await this.$http.get("/account/findAccountList", {
            params: this.queryMap
          });
          if (!res.data.success) {
            return this.$message.error("获取账户列表失败:" + res.data.data.errorMsg);
          }
          this.total = res.data.data.total;
          this.accountData = res.data.data.rows;
        } catch (error) {
          console.error("获取账户列表时出错", error);
        }
      },
      openAddDialog() {
        this.dialogTitle = '新建账户';
        this.accountForm = {
          accountId: "",
          customerId: "",
          accountName: "",
          lineType: "",
          accountValidity: "",
          company: "",
          platformType: "",
          accountType: "正常",
          customerType: "",
          openDate: "",
          afterSales: "",
          accountBalance: "",
          status: 0,

        };
        this.showDeptSelect = true
        this.dialogVisible = true;
      },
      openEditDialog(account) {
        console.log(account)
        this.dialogTitle = '修改账户';
        this.accountForm = { ...account };
        this.accountForm.accountId = account.accountId; // 假设你的数据行中有一个名为 'id' 的字段存储唯一标识
        this.accountForm.clientNo = account.clientNo;
        this.dialogVisible = true;
        this.showDeptSelect = false;
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },

      //添加账户
      async addAccount() {
        this.loading = true;
        try {
          this.btnLoading=true;
          this.btnDisabled=true;

          if (this.isLessThan(this.accountForm.agentNum,this.accountForm.seatsNumber)) {
            this.loading = false;
            console.log("签约坐席数:"+this.accountForm.agentNum+"坐席数:"+this.accountForm.seatsNumber)
            return this.$message.warning("坐席数不可大于签约坐席数");
          }
          this.accountForm.status = 0;
          const res = await this.$http.post('/account/addAccount', this.accountForm);
          if (res.data.success) {
            // 假设后端返回的res.data.data是更新后的账户对象
            const { id } = res.data.data;
            this.$message.success('账户信息更新成功');
            // 关闭抽屉
            this.dialogVisible = false;
            this.btnLoading=false;
            this.btnDisabled=false;

            // 弹出确认框
            this.$confirm('是否现在对帐号进行高级设置？', '提示', {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              // 用户点击确认按钮的操作
              console.log('用户点击了确认按钮');
              this.openSettingsWindows(res.data.data);

            }).catch(() => {

              // 用户点击取消按钮的操作
              console.log('用户点击了取消按钮');
            });

            // 重新获取账户列表，以显示更新后的数据
            await this.getAccountList();
            await this.findDeparmentClientList();
            return { id };
          } else {
            // 检查res.data.data是否存在
            if (res.data.data && 'errorMsg' in res.data.data) {
              this.$message.error('账户信息更新失败:' + res.data.data.errorMsg);
            } else {
              this.$message.error('账户信息更新失败，后端返回的数据结构异常');
            }
            return null;
          }
        } catch (error) {
          console.error('更新账户信息时出错', error);
          this.$message.error('更新账户信息时遇到异常，请检查网络或联系管理员');
          return null;
        } finally {
          this.loading = false;
        }
      },
// 修改账户
      async updateAccount() {
        // 简单校验，确保updataResourceInfo中有数据
        if (!this.accountForm || Object.keys(this.accountForm).length === 0) {
          return this.$message.error('没有可更新的账户信息');
        }
        // 检查是否有id
        if (!('accountId' in this.accountForm)) {
          return this.$message.error('账户id缺失，无法更新');
        }
        // 输出要修改的数据
        console.log('即将更新的账户数据:', this.accountForm);
        this.loading = true;
        if (this.isLessThan(this.accountForm.agentNum,this.accountForm.seatsNumber)) {
          this.loading = false;
          console.log("签约坐席数:"+this.accountForm.agentNum+"坐席数:"+this.accountForm.seatsNumber)
          return this.$message.warning("坐席数不可大于签约坐席数");
        }
        try {
          this.btnLoading = true;
          this.btnDisabled = true;

          console.log('开始请求 /account/chackCircuritIdIsChange');
          try {
            const chackResut = await this.$http.post('/account/chackCircuritIdIsChange', this.accountForm);
            console.log('请求 /account/chackCircuritIdIsChange 成功', chackResut);

            if (chackResut.data === 0) {
              console.log("需要更改账户的线路类型", chackResut.data);
              const updateResut = await this.$http.post('/account/updateUserCircuritIdByAccountName', this.accountForm);

              if(updateResut.data ===0){
                console.log("修改失败")
              }else{
                console.log("修改成功")
              }
            } else {
              console.log("不需要更改账户的线路类型", chackResut.data.data);
            }
          } catch (error) {
            console.error('请求 /account/chackCircuritIdIsChange 时出错', error);
            this.$message.error('检查线路类型时遇到异常，请检查网络或联系管理员');
            return null;
          }
          this.accountForm.accountName = null;
          const res = await this.$http.post('/account/updateAccountListById', this.accountForm);
          console.log('请求 /account/updateAccountListById 结果', res);
          if (res.data.success) {
            // 假设后端返回的res.data.data是更新后的账户对象
            const { id } = res.data.data;
            this.$message.success('账户信息更新成功');
            // 关闭抽屉
            this.dialogVisible = false;
            this.btnLoading = false;
            this.btnDisabled = false;
            // 重新获取账户列表，以显示更新后的数据
            await this.getAccountList();
            return { id };
          } else {
            // 检查res.data.data是否存在
            if (res.data.data && 'errorMsg' in res.data.data) {
              this.$message.error('账户信息更新失败:' + res.data.data.errorMsg);
            } else {
              this.$message.error('账户信息更新失败，后端返回的数据结构异常');
            }
            return null;
          }
        } catch (error) {
          console.error('更新账户信息时出错', error);
          this.$message.error('更新账户信息时遇到异常，请检查网络或联系管理员');
          return null;
        } finally {
          this.loading = false;
        }
      },

      //打开高级账户设置
      openSettingsWindows(account){
        console.log("得到的",account)
        this.accountForm = { ...account };
        console.log("accountForm",this.accountForm);
        this.accountForm.accountId = account.accountId; // 假设你的数据行中有一个名为 'id' 的字段存储唯一标识
        this.settingsWindow = true;
      },
      //a是否小于b
      isLessThan(a, b) {
        const diff = a - b;
        if (diff === 0) return false; // 相等时返回false

        // 使用DataView获取差值的二进制符号位
        const buffer = new ArrayBuffer(8);
        const view = new DataView(buffer);
        view.setFloat64(0, diff);
        const firstByte = view.getUint8(0); // 获取最高有效字节

        // 检查最高位的符号位（0x80对应二进制10000000）
        return (firstByte & 0x80) !== 0;
      },
      //修改账户
      async settings() {
        // 检查是否有id
        if (!('accountId' in this.accountForm)) {
          return this.$message.error('账户id缺失，无法更新');
        }
        // 输出要修改的数据
        console.log('即将更新的账户数据:', this.accountForm);
        this.loading = true;
        if (this.isLessThan(this.accountForm.agentNum,this.accountForm.seatsNumber)) {
          this.loading = false;
          console.log("签约坐席数:"+this.accountForm.agentNum+",坐席数:"+this.accountForm.seatsNumber)
          return this.$message.warning("坐席数不可大于签约坐席数");
        }
        //得到已使用的坐席数
        const {data:seatRes}=await this.$http.get('/comcentre/seats/getSeatsNumber',
            {
              params:this.accountForm
            }
        );
        if(this.isLessThan(this.accountForm.seatsNumber,seatRes.data.useSeatsNumbers)){
          return this.$message.warning("设置的坐席数不可小于该账户已使用的坐席数，该账户已使用"+seatRes.data.useSeatsNumbers+"个坐席");
        }
        //得到已使用的坐席数
        const {data:numInfoRes}=await this.$http.get('/system/zoning/getZoningSeatsNumber',
            {
              params:this.accountForm
            }
        );
        console.log("numInfoRes====================")
        console.log(numInfoRes)
        if(this.isLessThan(this.accountForm.seatsNumber,(numInfoRes.data.availableSeatsNum-numInfoRes.data.freeAvailableSeatsNum))){
          let msg ="设置的坐席数不可小于"+(numInfoRes.data.availableSeatsNum-numInfoRes.data.freeAvailableSeatsNum)+"个，该账户已分配给下级部门"+(numInfoRes.data.ofAssignedSeatsNum)+"个坐席名额,根部门下开启了"+(numInfoRes.data.availableSeatsNum-numInfoRes.data.freeAvailableSeatsNum-numInfoRes.data.ofAssignedSeatsNum)+"个外呼坐席";
          return this.$message.warning(msg);
        }

        try {
          this.btnLoading=true;
          this.btnDisabled=true;
          // this.accountForm.status=0;
          const res = await this.$http.post('/account/updateAccountListById', this.accountForm);
          if (res.data.success) {
            // 假设后端返回的res.data.data是更新后的账户对象
            const { id } = res.data.data;
            this.$message.success('高级设置信息更新成功');
            // 关闭抽屉
            this.settingsWindow = false;
            this.btnLoading=false;
            this.btnDisabled=false;
            // 重新获取账户列表，以显示更新后的数据
            await this.getAccountList();
            return { id };
          } else {
            // 检查res.data.data是否存在
            if (res.data.data && 'errorMsg' in res.data.data) {
              this.$message.error('账户信息更新失败:' + res.data.data.errorMsg);
            } else {
              this.$message.error('账户信息更新失败，后端返回的数据结构异常');
            }
            return null;
          }
        } catch (error) {
          console.error('更新账户信息时出错', error);
          this.$message.error('更新账户信息时遇到异常，请检查网络或联系管理员');
          return null;
        } finally {
          this.loading = false;
        }
      },

      /**
       * 获取线路列表
       */
      async getCircuitList(){
        const { data: res } = await this.$http.get("/bgCircuit/findList");
        if(!res.success){
          return this.$message.error("获取线路列表失败:"+res.data.errorMsg);
        }
        this.lineTypeList = res.data;
      },
  //删除账户
      async deleteAccount(account){
        this.loading = true;
        const confirm = await this.$confirm(
            "此操作将把该账户删除, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
        ).catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除操作"
          });
        });
        if(confirm === "confirm") {
          try {
            const res = await this.$http.get('/account/deleteAccountById', {
              params: {
                id: account.accountId
              }
            });
            // 假设后端返回1表示成功，其他值表示失败
            if (res.data === 1) {
              this.$message.success('账户删除成功');
              // 重新获取账户列表，以显示更新后的数据
              await this.getAccountList();
            } else {
              this.$message.error('账户删除失败');
            }
          } catch (error) {
            console.error('删除账户信息时出错', error);
            this.$message.error('删除账户信息时遇到异常，请检查网络或联系管理员');
          } finally {
            this.loading = false;
            this.getAccountList();
          }
        }
      },
      //删除账户
      async deleteUserByAccountName(account){
        this.loading = true;
        const confirm = await this.$confirm(
            "此操作将把归属该账号的用户一键清除, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
        ).catch(() => {
          this.$message({
            type: "info",
            message: "已取消一键清除操作"
          });
        });
        if(confirm === "confirm") {
          try {
            const res = await this.$http.get('/account/deleteUserByAccountName', {
              params: {
                accountName: account.accountName
              }
            });
            // 假设后端返回1表示成功，其他值表示失败
            if (res.data >= 1) {
              this.$message.success('一键清除成功');
              // 重新获取账户列表，以显示更新后的数据
              await this.getAccountList();
            } else {
              this.$message.error('一键清除失败');
            }
          } catch (error) {
            console.error('一键清除时出错', error);
            this.$message.error('一键清除时遇到异常，请检查网络或联系管理员');
          } finally {
            this.loading = false;
          }
        }
      }, //删除账户
      async updateUserByAccountName(account){
        this.loading = true;
        const confirm = await this.$confirm(
            "此操作将把归属该账号的用户以及其账户一键恢复, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
        ).catch(() => {
          this.$message({
            type: "info",
            message: "已取消一键恢复操作"
          });
        });
        if(confirm === "confirm") {
          try {
            const res = await this.$http.get('/account/updateUserByAccountName', {
              params: {
                accountName: account.accountName
              }
            });
            // 假设后端返回1表示成功，其他值表示失败
            if (res.data >= 1) {
              this.$message.success('一键恢复成功');
              // 重新获取账户列表，以显示更新后的数据
              await this.getAccountList();
            } else {
              this.$message.error('一键恢复失败');
            }
          } catch (error) {
            console.error('一键恢复时出错', error);
            this.$message.error('一键恢复时遇到异常，请检查网络或联系管理员');
          } finally {
            this.loading = false;
          }
        }
      },
      // 重置按钮事件
      reset() {
        this.queryMap = {
          pageNum: 1,
          pageSize: 10,
          clientName: "",
        };
      },
      /**
       * 加载部门列表
       */
      async findDeparmentClientList() {
        this.loading = true;
        try {
          const { data: res } = await this.$http.get("/account/findDeparmentClientList");
          console.log('获取客户类型列表响应数据:', res);
          let validData = [];
          if (Array.isArray(res)) {
            validData = res;
          } else if (typeof res === 'object' && res.success) {
            validData = res.data || [];
          }
          if (Array.isArray(validData)) {
            this.deptClientList = validData.map(item => ({
              deptId: item.deptId,
              deptName: item.deptName
            }));
          }
        } catch (error) {
          // 处理其他异常
          console.error('获取行业类型列表时遇到异常', error);
          this.$message.error('获取行业类型列表时遇到异常');
        }
      },
      /**
       * 加载客户类型列表
       */
      async findClienttypeList() {
        this.loading = true;
        try {
          const { data: res } = await this.$http.get("/account/findClienttypeList");
          console.log('获取客户类型列表响应数据:', res);
          let validData = [];
          if (Array.isArray(res)) {
            validData = res;
          } else if (typeof res === 'object' && res.success) {
            validData = res.data || [];
          }
          if (Array.isArray(validData)) {
            this.clienttypeList = validData.map(item => ({
              clientTypeId: item.clientTypeId,
              options: item.options
            }));
          }
        } catch (error) {
          // 处理其他异常
          console.error('获取行业类型列表时遇到异常', error);
          this.$message.error('获取行业类型列表时遇到异常');
        }
      },

      /**
       * 加载雇员列表
       */
      async findEmployeeList() {
        this.loading = true;
        try {
          const { data: res } = await this.$http.get("/account/findEmployeeList");
          console.log('获取客户类型列表响应数据:', res);
          let validData = [];
          if (Array.isArray(res)) {
            validData = res;
          } else if (typeof res === 'object' && res.success) {
            validData = res.data || [];
          }
          if (Array.isArray(validData)) {
            this.employeeList = validData.map(item => ({
              empId: item.empId,
              nickName: item.nickName
            }));
          }
        } catch (error) {
          // 处理其他异常
          console.error('获取行业类型列表时遇到异常', error);
          this.$message.error('获取行业类型列表时遇到异常');
        }
      },

      async checkAccountName() {
        // 检查 accountForm.accountName 是否为空
        if (this.accountForm.accountName === null || this.accountForm.accountName === "") {
          return;
        }
        try {
          const response = await this.$http.get("/account/findAccountCount", {
            params: {
              accountName: this.accountForm.accountName
            }
          });
          // 检查 response.data 的数据类型
          if (typeof response.data === 'number') {
            this.count = response.data;
            this.accountNameValid = (this.count === 0); // 根据返回结果更新标志位
            if (this.count === 1) {
              this.$message.error("账户名已存在");
            } else if (this.count === 0) {
              this.$message.success("账户名可用");
            } else {
              this.$message.warning("无法确定账户名是否可用，请检查返回数据");
            }
          } else {
            this.accountNameValid = false;
            this.$message.error("返回数据类型错误，请检查后端接口");
          }
        } catch (error) {
          this.accountNameValid = false;
          if (error.response) {
            // 处理 HTTP 错误状态码
            if (error.response.status === 400) {
              this.$message.error("请求参数错误，请检查输入的账户名称");
            } else if (error.response.status === 404) {
              this.$message.error("未找到相关服务，请联系管理员");
            } else if (error.response.status === 500) {
              this.$message.error("服务器内部错误，请联系管理员");
            } else {
              this.$message.error("查询账户名称时出错，请检查网络或联系管理员");
            }
          } else {
            // 处理其他错误，如网络错误
            this.$message.error("网络错误，请检查网络连接或联系管理员");
          }
          console.error("查询账户名称时出错", error);
        }
      },
      search(){

        this.getAccountList();
        this.getOpenDateTime();
        this.getIndateTime();
        console.log(this.queryMap.openDateStartTime)
      },
      handleSizeChange(newSize) {
        this.queryMap.pageSize = newSize;
        this.getAccountList();
      },
      handleCurrentChange(current) {
        this.queryMap.pageNum = current;
        this.getAccountList();
      },
      // 定义一个格式化时间的函数
      formatDate(date, is) {
        //判断时间是否为空
        if (date != null) {
          //判断是否为结束时间
          if (is) {
            date.setDate(date.getDate() + 1);
          }
          const year = date.getFullYear();
          //+1，是因为月份是从0开始
          const month = ('0' + (date.getMonth() + 1)).slice(-2);
          const day = ('0' + date.getDate()).slice(-2);
          // console.log('格式化前各部分值: 年:', year,'月:', month,'日:', day);
          const hours = ('0' + date.getHours()).slice(-2);
          const minutes = ('0' + date.getMinutes()).slice(-2);
          const seconds = ('0' + date.getSeconds()).slice(-2);
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
          // console.log('最终返回结果:', result);
        }
        return null;
      },
      //时间筛选
      getOpenDateTime() {
        if (this.openDate != null) {
          console.log("时间：", this.openDate)
          this.queryMap.openDateStartTime = this.formatDate(this.openDate[0], false)
          this.queryMap.openDateEndTime = this.formatDate(this.openDate[1], true)
        } else {
          this.queryMap.openDateStartTime = ""
          this.queryMap.openDateEndTime = ""
        }
      },
      //时间筛选
      getIndateTime() {
        if (this.indate != null) {
          console.log("时间：", this.indate)
          this.queryMap.indateStartTime = this.formatDate(this.indate[0], false)
          this.queryMap.indateEndTime = this.formatDate(this.indate[1], true)
        } else {
          this.queryMap.indateStartTime = ""
          this.queryMap.indateEndTime = ""
        }
      }
    },
    created() {
      this.getAccountList();
      this.findDeparmentClientList();
      this.findClienttypeList();
      this.findEmployeeList();
      this.getCircuitList();
      this.accountForm.clientTypeId = this.queryMap.clientTypeId;
      this.accountForm.circuitId = this.queryMap.circuitId;

    },
  };
  </script>

  <style scoped>
  .hint {
    margin-left: 2vh;
    font-weight: 400;
    font-size: 12px;
    color: red;
  }

  .el-row {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .el-row .el-col {
    font-size: 14px;

    label {
      color: #5e6d82;
    }
  }

  </style>